package cn.org.spring.wechar.service;

import cn.org.spring.common.util.HttpClientUtils;
import cn.org.spring.wechar.bean.AccessTokenBean;
import cn.org.spring.wechar.config.WeCharConfig;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class AccessTokenService {

    @Autowired
    private WeCharConfig weChatConfig;

    private AccessTokenBean accessTokenBean;
    //官方提供的固定地址
    private static final String URL = "https://api.weixin.qq.com/cgi-bin/token";

    private void refresAccessToken(String appId,String appSecret) throws IOException {
        String s = HttpClientUtils.get(URL, AccessTokenBean.requestOf(appId, appSecret));
        JSONObject jsonObject = JSONObject.parseObject(s);
        long expires = jsonObject.getLong("expires_in");
        String token  = jsonObject.getString("access_token");
        accessTokenBean = AccessTokenBean.responseOf(token, expires);
    }

    /**
     * 获取access 的 token
     * @return
     */
    public String getAccessToken() throws IOException {
        if (accessTokenBean == null || accessTokenBean.isExpiresTime()){
            refresAccessToken(weChatConfig.getAppId(),weChatConfig.getSecret());
        }
        return accessTokenBean.getAccessToken();
    }

    public static void main(String[] args) throws IOException {
        AccessTokenService accessTokenService = new AccessTokenService();
        accessTokenService.refresAccessToken("wxd1db2a66b0796762","7c6b73de18dc9c8c6dcc8ff2067678b0");
    }

}
